import Vue from 'vue'
import Vuex from 'vuex'
//导入car模块
// import Car from './module/cart.js'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    creator: '德玛西亚',
    list: [],
    newArr: []
  },
  getters: {
  },
  mutations: {
  },
  actions: {
    //获取图书列表
    async getbook (store) {
      // console.log(store);
      const res = await axios({
        url: 'http://hmajax.itheima.net/api/books',
        params: {
          creator: store.state.creator
        }
      })
      // console.log(res);
      store.state.list = res.data.data
    },
    //添加图书
    async addbook (store, obj) {
      const res = await axios({
        url: 'http://hmajax.itheima.net/api/books',
        method: 'post',
        data: {
          creator: store.state.creator,
          bookname: obj.bookname,
          author: obj.author,
          publisher: obj.publisher,
        }
      })
      store.dispatch('getbook')

    },
    //删除图书
    async delbook (store, id) {
      const res = await axios({
        url: 'http://hmajax.itheima.net/api/books/' + id,
        method: 'delete',
      })

      store.dispatch('getbook')
      // console.log(res);
    },
    //编辑获取图书数据
    editbook (store, id) {
      return new Promise(async (reslove, reject) => {
        const res = await axios({
          url: 'http://hmajax.itheima.net/api/books/' + id,
        })
        console.log(res);;
        store.state.newArr = store.state.list.filter(item => item.id == id)
        reslove(store.state.newArr)
      })
    },
    //修改图书
    async updatebook (store, obj, id) {
      const res = await axios({
        url: 'http://hmajax.itheima.net/api/books/' + id,
        method: 'put',
        data: {
          creator: store.state.creator,
          bookname: obj.bookname,
          author: obj.author,
          publisher: obj.publisher,
        }
      })
      console.log(res);
      store.dispatch('getbook')
    },

  },
  modules: {
  }
})
